<?php

namespace MoChat\App\Sales\Action\AllocationTask;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Sales\Constants\SalesTaskStatusCode;
use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\App\Sales\Contract\WorkDepartmentContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 销售任务列表
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SalesTaskContract
     */
    protected $salesTaskService;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesAllocationTask/list", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $where = [];
        if (!empty($data['work_department_id'])) {
            $where[] = ['work_department_id', '=', $data['work_department_id']];
        }
        if (!empty($data['start_time'])) {
            $where[] = ['start_time', '>=', $data['start_time']];
            $where[] = ['end_time', '<', $data['end_time']];
        }
        if (is_numeric($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        if (is_numeric($data['is_failure'])) {
            $nowTime = date('Y-m-d H:i:s');
            if ($data['is_failure'] == 1) {
                $where[] = ['end_time', '>', $nowTime];
            } else {
                $where[] = ['end_time', '<', $nowTime];
            }
        }

        if ($user['department']) {
            $where[] = ['work_department_id', '=', $user['department']];
        }
        $list = $this->salesTaskService->getSalesTaskList($where);
        if (!empty($list)) {
            $list['totalSalesTask'] = isset($list['data']) && !empty($list['data']) ? array_sum(array_column($list['data'], 'salesTask')) : 0;
            $list['allocatedSalesTask'] = isset($list['data']) && !empty($list['data']) ? array_sum(array_column($list['data'], 'allocatedSalesTask')) : 0;
            $list['unallocatedSalesTask'] = (float)bcsub($list['totalSalesTask'], $list['allocatedSalesTask'], 2);
        }
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$datum) {
                $dept = $this->workDepartmentService->getOneWorkDepartmentById($datum['workDepartmentId']);
                $datum['dept_name'] = !empty($dept) ? $dept['name'] : '';
                $datum['statusString'] = SalesTaskStatusCode::getMessage($datum['status']);
                $datum['failure'] = '未失效';
                if (strtotime($datum['endTime']) < time()) {
                    $datum['failure'] = '已失效';
                }
                unset($datum['status']);
            }
            unset($datum);
        }
        return $list;
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'work_department_id' => 'integer',
            'page' => 'required|integer',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'work_department_id.integer' => '部门参数错误',
            'page.required' => '分页参数错误',
            'page.integer' => '分页参数错误',
        ];
    }
}